(function(angular) {
	"use strict";
	angular.module("fs.waf").factory("glEntryService", glEntryService);
	glEntryService.$inject = [ "$q", "ajaxServiceFactory", "gridService"];
	function glEntryService($q, ajaxServiceFactory, gridService) {

		function getSetlItemTypeOptions() {
			var ajaxService = ajaxServiceFactory.buildAjaxService({
				getSetlItemTypes : {
					url : "do/cda/dataList/setlItemTypes",
					method : "post"
				}
			});
			return $q(function(resolved, rejected) {
				ajaxService.getSetlItemTypes({}).then(function(response) {
					resolved(response ? response.data : []);
				}, angular.noop);
			});
		} 
		
		function getGlentryList($scope, layoutConfig, txnId, txnType){
			var ajaxService = ajaxServiceFactory.buildAjaxService({
				getGlentryList : {
					url : "do/cls/glentry/loanGlEntryList",
					method : "post"
				}
			}), defer = $q.defer(), glEntryList = [], 
			glEntryListConfig = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.glEntryList.tableConfigs.table, null);
			glEntryListConfig.data = "vm.glEntryList";
			glEntryListConfig.enableRowHeaderSelection = false;
			ajaxService.getGlentryList({txnId : txnId, txnType : txnType}).then(function(response) {
				angular.merge(glEntryList, response.data.list);
				processList(glEntryList);
				defer.resolve({
					glEntryListConfig : glEntryListConfig,
					glEntryList : glEntryList
				});
			},angular.noop);
			return defer.promise;
		};
		
		function processList(glEntryList){
			if(glEntryList && glEntryList.length > 0){
				var itemCcy = "", crDr = "";
				for(var i = 0; i < glEntryList.length; i++){//add item for sub list
					//For formatting
					glEntryList[i].itemCcy_cache = glEntryList[i].itemCcy;
					if(itemCcy == glEntryList[i].itemCcy && crDr == glEntryList[i].crDr){
						glEntryList[i].itemCcy = "";
						glEntryList[i].crDr = "";
					}else if(itemCcy == glEntryList[i].itemCcy){
						glEntryList[i].itemCcy = "";
						crDr = glEntryList[i].crDr;
					}else{
						itemCcy = glEntryList[i].itemCcy;
						crDr = glEntryList[i].crDr;
					}
				}
			}
		}
		
		return {
			getGlentryList : getGlentryList,
			getSetlItemTypeOptions : getSetlItemTypeOptions
		};
		
	}
})(angular);